<script setup lang="ts">
  import { ref } from "vue";
  import { Filter } from "@/components/SideBar";
  import Dialog from "@/components/sql/Dialog.vue";
  // import { AwesomeQR } from "awesome-qr";
  import JSZip from "jszip";
  import { Workbook } from "exceljs";
  import { formatDate } from "@/util";
  let searchTime: [number, number] | undefined = undefined;
  function getDefaultTime() {
    const t = new Date(), a = new Date(t.getFullYear(), t.getMonth(), t.getDate(), 0, 0, 0, 0);
    return [new Date(t.getFullYear(), t.getMonth(), t.getDate(), 0, 0, 0, 0),
    new Date(a.getTime() + 86400000 - 1)
    ];
  }
  const fd: RequiredKey<gt.components.SideBar.Filter, "opt">[] = [
    {
      value: "新增", type: "button", opt: {
        async onClick() {
          click(0, format.def.voucher);
        }, type: "primary", class: "mac-ico-add-round"
      },
    },
    {
      label: "生成时间", value: [], type: "datePicker", opt: {
        type: "datetimerange", startPlaceholder: "起始时间", endPlaceholder: "结束时间", clearable: true,
        defaultTime: getDefaultTime(), onChange(e: [Date, Date] | null) {
          searchTime = e ? [parseInt(e[0].getTime() / 1000), parseInt(e[1].getTime() / 1000)] : undefined;
          init();
        }
      }
    },
    {
      value: "生成二维码", type: "button", opt: {
        type: "danger", async onClick() {
          return msg("暂停使用二维码生成");
          const domain = await gd.setting.getById("wxpub") as gt.sql.setting;
          ElMessageBox({
            title: "生成二维码",
            message: `当前将生成(${page.value.total})个二维码,是否继续?`,
            type: "warning",
            callback() { },
            async beforeClose(action, _instance, done) {
              const loading = ElLoading.service({ text: "正在生成,请稍后..." });
              if (action == "confirm") {
                const r: string[] = await api.request({ "#rule": [{ field: "createTime", logic: "between", value: searchTime }] }, "voucher/ids");
                const zip = new JSZip();
                await Promise.all(r.map(async (e) => {
                  const buffer = (await new AwesomeQR({ text: `${domain.value}?Voucher=${e}` }).draw()) as string;
                  zip.file(e + ".png", buffer.substring(22), { base64: true });
                }));
                zip.generateAsync({ type: "blob" }).then((content) => {
                  const a = document.createElement("a");
                  a.download = "代金券二维码.zip";
                  a.href = URL.createObjectURL(content);
                  a.click();
                  URL.revokeObjectURL(a.href);
                  a.remove();
                });
              }
              loading.close();
              done();
            },
          });
        }, disabled: true
      }
    },
    {
      value: "导出卡密", type: "button", opt: {
        type: "success", async onClick() {
          ElMessageBox({
            title: "导出卡密",
            message: `当前将生成(${page.value.total})条数据,是否继续?`,
            type: "warning",
            callback() { },
            async beforeClose(action, _instance, done) {
              const loading = ElLoading.service({ text: "正在生成,请稍后..." });
              try {
                if (action == "confirm") {
                  const r: obj[] = await api.request({
                    "#rule": [{ field: "createTime", logic: "between", value: searchTime }],
                    "#order": [["money", "ASC"]],
                  }, "voucher/read");
                  const workbook = new Workbook(),
                    worksheet = workbook.addWorksheet("卡密");
                  worksheet.columns = [
                    { header: "ID", key: "id", width: 20 },
                    { header: "创建时间", key: "_createTime", width: 20 },
                    { header: "使用时间", key: "_changeTime", width: 20 },
                    { header: "名称", key: "name", width: 20 },
                    { header: "金额", key: "money", width: 20 },
                    { header: "卡号", key: "prefix", width: 20 },
                    { header: "密码", key: "suffix", width: 20 },
                  ];
                  worksheet.addRows(r.map(e => {
                    const idl = e.id.length - 6;
                    return {
                      id: e.id, _createTime: formatDate(e.createTime), _changeTime: formatDate(e.changeTime), name: e.name,
                      money: (e.money / 100).toFixed(2), prefix: e.id.substring(0, idl), suffix: e.id.substring(idl)
                    };
                  }));
                  const buffer = await workbook.xlsx.writeBuffer();
                  const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
                  const link = document.createElement('a');
                  link.href = URL.createObjectURL(blob);
                  link.download = '卡密.xlsx';
                  link.click(); // 模拟点击下载文件
                  await next();
                  URL.revokeObjectURL(link.href);
                  link.remove();
                }
              } catch (_) { }
              loading.close();
              done();
            },
          });
        }, disabled: true
      }
    }
  ],
    page = ref<gt.PageData<gt.sql.voucher>>({ current: 1, size: 10, total: 0, data: [] }),
    filterData = ref<any>(fd),
    tip = ref([
      { label: "复制添加代金券", value: 0, cls: "mac-ico-add-round", per: api.me.per("代金券创建") },
      { label: "编辑代金券", value: 1, cls: "mac-ico-edit", per: false },
      { label: "查看代金券", value: 2, cls: "mac-ico-search", per: true },
      { label: "删除代金券", value: 3, cls: "mac-ico-delete", per: api.me.per("代金券删除") },
    ] as const),
    dig = ref({} as InstanceType<typeof Dialog>),
    refreshFilter = ref(0)
    ;
  async function click(method: number, p: gt.sql.voucher) {
    switch (method) {
      case 0: // 新增
        p = Object.assign({}, p, { id: "" });
        break;
      case 1: // 修改
        break;
      case 2: // 查看
        break;
      case 3: // 删除
        break;

      default:
        return;
    }
    await dig.value.open("voucher", method, p, "代金券二维码");
    init();
  }

  async function init() {
    const loading = ElLoading.service({ text: "正在读取数据,请稍后..." }),
      rule: QueryPage<gt.sql.voucher> = {
        "#page": { current: page.value.current, size: page.value.size },
        "#rule": [],
        "#order": [["createTime", "DESC"]]
      };
    fd[3].opt.disabled = fd[2].opt.disabled = !searchTime;
    fd[0].opt.disabled = !api.me.per("代金券创建");
    if (searchTime) {
      rule["#rule"]?.push({ field: "createTime", logic: "between", value: searchTime });
    }
    const res = await gd.voucher.read(rule);
    page.value = res;
    refreshFilter.value ^= 1;
    loading.close();
  }
  init();
</script>
<template>
  <LayoutPage>
    <div class="voucher whf oh y">
      <div class="mac-ico-warning">请选择时间筛选后,才可生成/导出 数据</div>
      <Filter :data="filterData" isRow class="mb1em" :key="refreshFilter" />
      <el-table stripe highlight-current-row :data="page.data" class="wf fg1" type="expand" row-key="id">
        <el-table-column prop="id" label="id" width="100" show-overflow-tooltip />
        <el-table-column prop="_createTime" label="创建时间" show-overflow-tooltip width="170" />
        <el-table-column prop="name" label="名称" show-overflow-tooltip width="200" />
        <el-table-column prop="use" label="兑付人id" show-overflow-tooltip width="80" />
        <el-table-column prop="image" label="图片" show-overflow-tooltip className="columnimg">
          <template #default="{ row }">
            <img :src="row.image" v-if="row.image" />
          </template>
        </el-table-column>
        <el-table-column prop="money" label="金额(分)" show-overflow-tooltip width="120" />
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <div class="buttons x zb">
              <template v-for="a in tip">
                <el-tooltip v-if="a.per" :content="a.label">
                  <div :class="a.cls" @click.stop="click(a.value, row)" />
                </el-tooltip>
              </template>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination background layout="prev, pager, next, jumper, ->, sizes, total"
        :page-sizes="[10, 20, 30, 40, 50, 100]" v-model:page-size="page.size" :total="page.total"
        v-model:currentPage="page.current" @size-change="init" @current-change="init" />
      <Dialog ref="dig" />
    </div>
  </LayoutPage>
</template>
<style lang="scss" scoped>
  .voucher {
    position: relative;
    >.mac-ico-warning {
      color: var(--color-info);
      width: 100%;
      text-align: center;
      &::before {
        color: var(--color-warning);
        margin-right: 0.4em;
      }
    }
    :deep(.columnimg) {
      padding: 0;
      >div {
        >img {
          max-height: 2.86em;
        }
      }
    }
    .whf {
      min-height: 1em;
    }
    .buttons {
      >div {
        cursor: pointer;
        padding: 0 0.4em;
        font-weight: 600;
        &:hover {
          border: 1px solid #a5a5a5;
          box-sizing: border-box;
          border-radius: 0.5em;
          box-shadow: 0 0 10px #000;
        }
      }
      >.mac-ico-add-round, >.mac-ico-people-list {
        color: var(--color-success);
      }
      >.mac-ico-edit, >.mac-ico-warning {
        color: var(--color-warning);
      }
      >.mac-ico-search {
        color: var(--color-primary);
      }
      >.mac-ico-delete, >.mac-ico-my {
        color: var(--color-error);
      }
    }
    .el-table {

      .blueRow {
        color: blue;
      }
      .redRow {
        color: red;
      }
    }
  }
</style>